﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using SeizyUtils;
using SeizyUtils.Common.Utilities;
using SeizyUtils.AppCode.Common.Data.Csv;

namespace SeizyUtils.Common.Data.Csv
{
    class CsvWriter : ICsvWriter<IRecord>
    {
        private readonly HandyFile _file;

        private StreamWriter _writer;

        private bool _isFirst = true;

        public CsvWriter(HandyFile file)
        {
            _file = file;
            _writer = new StreamWriter(_file.getFileStream(FileMode.Create), Encoding.GetEncoding("Shift-JIS"));
        }

        public void writeLine(IRecord record)
        {
            string result;
            if (_isFirst)
            {
                _isFirst = false;
                result = createColumnLine(record);
                _writer.WriteLine(result);
            }
            result = createLine(record);
            _writer.WriteLine(result);
        }


        public void close()
        {
            _writer.Close();
        }

        private static string createColumnLine(IRecord record)
        {
            StringBuilder builder = new StringBuilder();
            ColumnModel _model = record.getColumnModel();
            for (int i = 0; i < _model.getSize(); i++)
            {
                if (builder.Length > 0)
                {
                    builder.Append(",");
                }
                builder.Append(CsvHelper.escapeQuato(_model.getColumnName(i)));
            }
            return builder.ToString();
        }

        private static string createLine(IRecord record)
        {
            StringBuilder builder = new StringBuilder();
            ColumnModel model = record.getColumnModel();
            for (int i = 0; i < model.getSize(); i++)
            {
                if (builder.Length > 0)
                {
                    builder.Append(",");
                }
                IColumn column = DefinitionManager.getColumn(model.getColumnName(i));
                builder.Append(CsvHelper.escapeQuato(record.GetObject(column).ToString()));
            }
            return builder.ToString();
        }


        #region IDisposable メンバ

        public void Dispose()
        {

            // ファイルを閉じる
            close();

        }

        #endregion
    }
}
